<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <button>点击取消请求</button>
    <div id="result"></div>
    <script>
        const btn = document.querySelectorAll("button");
        const result = document.querySelector("#result");

        let xhr = null;
        let isSending = false;  // 用于标识请求是否正在发送
        btn[0].onclick = function() {
            if(isSending){
                // 正在发送，则取消之前的所有请求，使用最、新的请求
                xhr.abort();
            }
            xhr = new XMLHttpRequest();
            isSending = true;
            xhr.open("GET", "http://127.0.0.1:8000/delay");
            xhr.send();
            xhr.onreadystatechange = function() {
                if(xhr.readyState === 4) {
                    // 服务端返回了结果
                    isSending = false;
                }
            }
        }
        btn[1].onclick = function() {
            // abort 方法用于手动取消ajax请求
            xhr.abort();
            
        }
        
        
    </script>
</body>
</html>